package com.hualan.Util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtil {

    public static Connection connection;
    public static DataSource dataSource;

    static {
        //创建数据库连接池对象
        //自动读取c3p0-config.xml文件找到默认的数据库连接配置，创建数据源
        dataSource = new ComboPooledDataSource();

    }

    public static Connection open() {
        //2、创建连接
        try {
            connection =  dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    public static void close(ResultSet rs, Statement statement, Connection connection) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if (connection != null) {
            try {
                //如果是new的连接，销毁，如果是从连接池中获取的连接，自动归还到连接池
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
